package com.bw.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bw.util.ScheduleConstants;
import com.bw.util.ScheduleUtils;
import com.bw.util.TaskException;
import com.bw.domain.SysJob;
import com.bw.service.SysJobService;
import com.bw.mapper.SysJobMapper;
import org.quartz.JobDataMap;
import org.quartz.JobKey;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.quartz.Scheduler;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * @author xiaoabiao
 * @description 针对表【sys_job(定时任务调度表)】的数据库操作Service实现
 * @createDate 2023-08-15 15:55:26
 */
@Service
public class SysJobServiceImpl extends ServiceImpl<SysJobMapper, SysJob>
        implements SysJobService {

    @Autowired
    private Scheduler scheduler;

    @Autowired
    private SysJobMapper sysJobMapper;
    /**
     * Trigger : 触发器
     * Scheduler : 调度器
     * 任务 ：JobDetail
     */

    /**
     * 项目启动时，初始化定时器,主要是防止手动修改数据库导致未同步到定时任务处理
     */
    @PostConstruct
    public void init() throws SchedulerException, TaskException {
        scheduler.clear();
        List<SysJob> list = sysJobMapper.selectJobAll();
        System.out.println("66666666666" + list);
        for (SysJob job : list) {
            ScheduleUtils.createScheduleJob(scheduler, job);
        }
    }

    @Override
    public IPage<SysJob> selectPageVo(IPage<?> page, SysJob sysJob) {
        return baseMapper.selectPageVo(page, sysJob);
    }

    @Override
    public List<SysJob> selectJobList(SysJob sysJob) {
        return baseMapper.selectJobList(sysJob);
    }


    @Override
    @Transactional
    public int inserts(SysJob sysJob) throws SchedulerException, TaskException {
        sysJob.setStatus(ScheduleConstants.Status.PAUSE.getValue());
        int rows = sysJobMapper.inserts(sysJob);
        if (rows > 0) {
            //创建定时任务
            System.out.println("创建定时任务");
            ScheduleUtils.createScheduleJob(scheduler, sysJob);

        }
        return rows;
    }

    /**
     * 更新cron时间表达式
     * @param sysJob
     * @return
     * @throws SchedulerException
     * @throws TaskException
     */
    @Override
    @Transactional
    public int updateJob(SysJob sysJob) throws SchedulerException, TaskException {
        SysJob job = getByIds(sysJob.getJobId());
        int i = sysJobMapper.updateJob(sysJob);
        if (i > 0) {
            upfates(sysJob, job.getJobGroup());
        }
        return i;
    }

    /**
     * 更新任务
     *
     * @param sysJob
     * @param jobGroup
     * @throws SchedulerException
     * @throws TaskException
     */
    private void upfates(SysJob sysJob, String jobGroup) throws SchedulerException, TaskException {
        Long jobId = sysJob.getJobId();
        //构建任务对象
        JobKey jobKey = ScheduleUtils.getJobKey(jobId, jobGroup);
        //判断任务是否存在
        if (scheduler.checkExists(jobKey)) {
            //先删除在添加
            //防止创建时存在数据问题 先移除，然后在执行创建操作
            scheduler.deleteJob(jobKey);
        }
        ScheduleUtils.createScheduleJob(scheduler, sysJob);
    }

    @Override
    public SysJob getByIds(Long id) {
        return baseMapper.getByIds(id);
    }

    /**
     * 任务调度状态修改
     *
     * @param
     * @return 结果
     */
    @Override
    @Transactional
    public int updatestatus(SysJob byId) throws SchedulerException {
        int i = 0;
        String status = byId.getStatus();
        if (ScheduleConstants.Status.NORMAL.getValue().equals(status)) {
            i = resumeJob(byId);
        } else if (ScheduleConstants.Status.PAUSE.getValue().equals(status)) {
            i = pauseJob(byId);
        }
        return i;
    }

    /**
     * 恢复任务
     *
     * @param job 调度信息
     */
    @Override
    @Transactional
    public int resumeJob(SysJob job) throws SchedulerException {
        Long jobId = job.getJobId();
        String jobGroup = job.getJobGroup();
        job.setStatus(ScheduleConstants.Status.NORMAL.getValue());
        int rows = sysJobMapper.updateJob(job);
        if (rows > 0) {
            scheduler.resumeJob(ScheduleUtils.getJobKey(jobId, jobGroup));
        }
        return rows;
    }

    /**
     * 暂停任务
     *
     * @param job 调度信息
     */
    @Override
    @Transactional
    public int pauseJob(SysJob job) throws SchedulerException {
        Long jobId = job.getJobId();
        String jobGroup = job.getJobGroup();
        job.setStatus(ScheduleConstants.Status.PAUSE.getValue());
        int rows = sysJobMapper.updateJob(job);
        if (rows > 0) {
            scheduler.pauseJob(ScheduleUtils.getJobKey(jobId, jobGroup));
        }
        return rows;
    }

    @Override
    @Transactional
    public void delJobByIds(String[] split) throws SchedulerException {
        for (String s : split) {
            Long aLong = Long.valueOf(s);
            SysJob byIds = sysJobMapper.getByIds(aLong);
            deleteJob(byIds);
        }
    }

    /**
     * 删除任务后，所对应的trigger也将被删除
     *
     * @param job 调度信息
     */
    @Override
    @Transactional
    public int deleteJob(SysJob job) throws SchedulerException {
        Long jobId = job.getJobId();
        String jobGroup = job.getJobGroup();
        int rows = sysJobMapper.deleteJobById(jobId);
        if (rows > 0) {
            scheduler.deleteJob(ScheduleUtils.getJobKey(jobId, jobGroup));
        }
        return rows;
    }

    /**
     * \
     * 立即运行
     *
     * @param sysJob
     */
    @Override
    public void run(SysJob sysJob) throws SchedulerException {
        Long jobId = sysJob.getJobId();
        String jobGroup = sysJob.getJobGroup();
        JobDataMap jobDataMap = new JobDataMap();
        /** 执行目标key */
        SysJob mapperByIds = sysJobMapper.getByIds(sysJob.getJobId());
        jobDataMap.put(ScheduleConstants.TASK_PROPERTIES, mapperByIds);
        scheduler.triggerJob(ScheduleUtils.getJobKey(jobId, jobGroup), jobDataMap);
    }
}




